<?php


class ArticleMetaImages extends Article
{
    public $keyName = "images";

    /**
     * @param $aid
     * @param $images
     */
    public function setImages($aid, $images)
    {
        !is_array($images) && $images = [];
        $oldImages = $this->getImagesByArticle($aid);

        $needAdds = array_diff($images, $oldImages);
        $needRemoves = array_diff($oldImages, $images);

        foreach ($needAdds as $needAdd){
            $metaModel = new self([
                'aid' => $aid,
                'key' => $this->keyName,
                'value' => $needAdd
            ]);
            $metaModel->save();
        }

        foreach ($needRemoves as $needRemove){
            self::model()->findOne('`key`=:key AND value=:value AND aid=:aid',array(':key'=>$this->keyName,':value'=>$needRemove,':aid'=>$aid))->delete();
            if( strpos( strrev($needRemove), '/' ) === 0 ){
                $fullName = Yii::getAlias('/uploads') . $needRemove;
            }else{
                $fullName = Yii::getAlias('/uploads') . $needRemove;
            }
            @unlink($fullName);
        }
    }

    /**
     * @param $aid
     * @return int|string
     */
    public function getImagesCount($aid)
    {
        return self::model()->countByAttributes('aid',array('aid=:aid','`key`=:key','params'=>array(':aid'=>$aid,':key'=>$this->keyName)));
    }

    public function getImagesByArticle($aid)
    {
        $result = self::model()->findAll('`key`=:key AND aid=:aid',array(':key'=>$this->keyName,':aid'=>$aid));
        var_dump($result);exit;

        foreach ($result as $key=>$value){
            $resultTemp[] = $value;
        }
        $result = array_column($resultTemp, 'value');
        return $result;
    }
}